package xyz.erupt.flow.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import xyz.erupt.flow.bean.entity.OaWorkFlowDefinition;

import java.util.List;

public interface OaWorkFlowDefinitionRepository extends JpaRepository<OaWorkFlowDefinition,Long> {

    /**
     * 根据groupid和关键词查询该组内所有工作流定义的最新版本并通过顺序排序
     * @param groupId 流程组id
     * @param keyword formName关键词
     * @return
     */
    @Query("from oa_work_flow_definition o1 where "+
            "((:groupId = 0L and o1.workFlowGroup.groupId is null and o1.stop = false) or (:groupId = -1L and o1.stop = true) " +
            "or (o1.workFlowGroup.groupId=:groupId and o1.stop = false)) " +
            "and (o1.formName like concat('%',:keyword,'%'))" +
            "and o1.version=(select max(o2.version) from oa_work_flow_definition o2 where o2.processKey=o1.processKey)" +
            "order by o1.version desc ,o1.sort asc ")
    List<OaWorkFlowDefinition> listByGroupId(Long groupId, String keyword);

    /**
     * 通过流程键获取该流程实例的最新版本排序列表
     * @param processKey 流程键
     * @return
     */
    @Query("from oa_work_flow_definition where processKey=:processKey order by version desc ")
    List<OaWorkFlowDefinition> LastVersions(String processKey);

    /**
     * 通过流程键获取该流程实例的最新版本
     * @param processKey
     * @return
     */
    default OaWorkFlowDefinition LastVersion(String processKey) {
        List<OaWorkFlowDefinition> oaWorkFlowDefinitions = LastVersions(processKey);
        return oaWorkFlowDefinitions.isEmpty() ? null : oaWorkFlowDefinitions.get(0);
    }

    /**
     * 获取最新版本的，版本号
     * @param processKey
     * @return
     */
    default Long LastVersionNum(String processKey) {
        OaWorkFlowDefinition oaWorkFlowDefinition = LastVersion(processKey);
        return oaWorkFlowDefinition == null ? 0L : oaWorkFlowDefinition.getVersion();
    }
}
